//
//  SearchItemViewController.m
//  NC-Trendy
//
//  Created by LeungChaos on 16/2/25.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "SearchItemViewController.h"
#import "SearchItemCell.h"
@interface SearchItemViewController ()<UITableViewDataSource, UITableViewDelegate>
///显示所有item的tableView
@property (nonatomic, weak) UITableView *tableView;
///保存所有item的数组
@property (nonatomic, strong) NSMutableArray<NCItem *> *itemArray;
///保存所有item中最小的item_id
@property (nonatomic, assign) NSInteger min_id;
///保存当前搜索字符
@property (nonatomic, copy) NSString *currentStr;
//转圈
@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic, copy) NSString *currentFrame;

@end

@implementation SearchItemViewController

- (UITableView *)tableView {
    if (_tableView == nil) {
        //创建tableView
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviBarH, MainScreenWidth, MainScreenHeight - kNaviBarH) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        _tableView = tableView;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

//懒加载item数组
- (NSMutableArray *)itemArray {
    if (_itemArray == nil) {
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

//设置键盘属性

- (void)viewDidLoad {
    [super viewDidLoad];
    //发送网络请求
    if (self.searchDict) {
        [self sendHttpRequestDict:self.searchDict];
        self.currentStr = self.searchDict[@"searchStr"];
    }
    //转圈
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hud show:YES];
     //设置上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (self.min_id && self.currentStr.length > 0) {
            NSDictionary *dict = @{@"min_item_id":@(self.min_id),@"searchStr":self.currentStr};
            //发送网络请求
            [self sendHttpRequestDict:dict];
        }
        //停止刷新
        [self.tableView.mj_footer endRefreshing];
    }];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //隐藏tabBar
    NSLog(@"search %@",NSStringFromCGRect(self.tableView.frame));
   RootTabBarViewController *rootView = (RootTabBarViewController *)[AppDelegate shareAppDelegate].window.rootViewController;
    rootView.isHide = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //显示tabBar
    NSLog(@"search %@",NSStringFromCGRect(self.tableView.frame));
    RootTabBarViewController *rootView = (RootTabBarViewController *)[AppDelegate shareAppDelegate].window.rootViewController;
    rootView.isHide = NO;
    //[self.tableView setFrame:self.view.frame];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.tableView setFrame:self.view.frame];
}

//发送网络请求时调用
- (void)sendHttpRequestDict:(NSDictionary *)dict {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //url服务器请求接口
    NSString *urlPath = [NSString stringWithFormat:@"%@/%@/%@",Localhost,Article,aSearchItems];
    //发送get请求
    [manager GET:urlPath parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
         NSLog(@"%@",[responseObject class]);
        //判断响应对象是否NSData类型的数据
        if ([responseObject isKindOfClass:[NSData class]]) {
            //解析json
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            //判断返回的状态是否成功
            if ([jsonDic[@"status"]isEqualToString:@"1"]) {
                //数组接收数据
                NSArray *array = [NSArray arrayWithArray:jsonDic[@"data"]];
                //遍历
                [array enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    //初始化item
                    NCItem *item = [[NCItem alloc]initWithDic:obj];
                    //添加到item数组里
                    [self.itemArray addObject:item];
                }];
                //排序
                [self.itemArray sortUsingComparator:^NSComparisonResult(NCItem *_Nonnull obj1, NCItem *_Nonnull obj2) {
                    //倒序
                    if ([obj2.item_id integerValue] > [obj1.item_id integerValue]) {
                        return YES;
                    } else {
                        return NO;
                    }
                    //return [obj2.item_id compare:obj1.item_id];
                }];
                //保存最小id
                NCItem *minItem = [self.itemArray lastObject];
                self.min_id = [minItem.item_id integerValue];
                NSLog(@"%ld",self.min_id);
                //刷新tableView
                [self.tableView reloadData];
                self.tableView.mj_footer.hidden = YES;
            } else {
                NSLog(@"no data");
            }
        }
        [self.hud hide:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            //请求失败
            NSLog(@"%@",error);
        }
    }];
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.itemArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //加载cell
    SearchItemCell *cell = [SearchItemCell searchCellWithTableView:tableView];
    //设置cell的item
    cell.ncItem = self.itemArray[indexPath.row];
    return cell;
}


#pragma mark - UITableViewDelegate
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //拿到cell的item
    NCItem *item = self.itemArray[indexPath.row];
    //初始化webView
    WebViewController *webView = [[WebViewController alloc]init];
    //传文章id 让webView加载此文章
    webView.artcle_id = item.article_id;
    [self.navigationController pushViewController:webView animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}



@end

